/**
 * Created by Administrator on 2017/6/1.
 */
window.onload = function () {
    function $(id) {
        return document.getElementById(id);
    }

    var js_slider = $("js_slider"); //   获取最大的盒子
    var slider_main_block = $("slider_main_block");
    var slider_ctrl = $("slider_ctrl");
    // 图片集合
    var imgs = slider_main_block.children;

    // 生成指示器
    for (var i = 0; i < imgs.length; i++) {
        var span = document.createElement("span");
        span.className = "slider-ctrl-con";
        span.innerHTML = i + 1;
        slider_ctrl.insertBefore(span, slider_ctrl.children[slider_ctrl.children.length - 1]);
    }

    var spans = slider_ctrl.children;
    spans[1].setAttribute("class", spans[1].getAttribute("class") + " current");

    var scrollWidth = js_slider.offsetWidth;
    for (var i = 1; i < imgs.length; i++) {
        imgs[i].style.left = scrollWidth + 'px';
    }
    // 遍历三个按钮
    var iNow = 0;
    for (k in spans) {
        spans[k].onclick = function () {
            if (this.className == "slider-ctrl-prev") {
                animate(imgs[iNow], {left: scrollWidth});
                --iNow < 0 ? iNow = imgs.length - 1 : 0;
                imgs[iNow].style.left = -scrollWidth + 'px';
                animate(imgs[iNow], {left: 0});
                setSquare(iNow);
            } else if (this.className == "slider-ctrl-next") {
                autoPlay();
            } else {
                var index = parseInt(this.innerHTML) - 1;
                if (index > iNow) {
                    animate(imgs[iNow], {left: -scrollWidth});
                    imgs[index].style.left = scrollWidth + 'px';
                } else if (index < iNow) {
                    animate(imgs[iNow], {left: scrollWidth});
                    imgs[index].style.left = -scrollWidth + 'px';
                }
                iNow = index;
                animate(imgs[iNow], {left: 0});
                setSquare(iNow);
            }
        }
    }

    function setSquare(index) {
        for (var i = 1; i < spans.length-1; i++) {
            spans[i].className = "slider-ctrl-con";
        }
        spans[index+1].className = 'slider-ctrl-con current';
    }

    // 自动播放
    var timer = null;
    timer = setInterval(autoPlay,5000);
    function autoPlay() {
        animate(imgs[iNow], {left: -scrollWidth});
        ++iNow > imgs.length - 1 ? iNow = 0 : iNow;
        imgs[iNow].style.left = scrollWidth + 'px';
        animate(imgs[iNow], {left: 0});
        setSquare(iNow);
    }

    js_slider.onmouseover = function () {
        clearInterval(timer);
    }

    js_slider.onmouseout = function () {
        clearInterval(timer);
        timer = setInterval(autoPlay,5000);
    }

}